$(function () {
    //1 获取裁剪区域的DOM元素
    const $image = $('#image')
    const opstions = {
        aspectRatio: 1,
        preview: '.img-preview'
    }
    $image.cropper(opstions)

    $('#btnChooseImg').on('click', function () {
        $('#file').click()
    })

    $('#file').on('change', function (e) {
        const files = e.target.files
        if (files.length === 0) return
        const imgURL = URL.createObjectURL(files[0])

        $image.cropper('destroy')
        $image.attr('src', imgURL)
        $image.cropper(opstions)
    })
    //为上传头像的按钮绑定点击事件处理函数
    $('#btnUploadImg').on('click', function () {
        const base64Img = $image
            .cropper('getCroppedCanvas', {
                width: 100,
                height: 100
            })
            .toDataURL('image/png')

        $.post('/my/update/avatar', { avatar: base64Img }, function (res) {
            if (res.status === 0) {
                window.parent.getUserInfo()
            }
            layer.msg(res.message)
        })
    })
})